<template>
  <PageWrapper title="提成结算">
    <div id="commission">
      <a-card>
        <a-row justify="space-between" class="top my-4 mx-4"><a-col>
            <a-space> 年度: <a-date-picker v-model:value="currentMonth" picker="month" @change="changePicker"
                format="YYYY-MM" valueFormat="YYYY-MM" />
            </a-space>
          </a-col><a-col>
            <a-space>
              <a @click="addInfo">资料录入</a>
              <a @click="addOrder">上传单据</a>
              <a @click="openRegister">注册密码</a>
            </a-space>
          </a-col>
        </a-row>

        <div class="ant-basic-table">
          <a-table class="ant-table-striped" :columns="columns" size="small" :data-source="dataSource" bordered
            :row-selection="rowSelection" :pagination="false" :scroll="{ x: 1400 }" rowKey="parnterId">
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'billUrl'">
                <a-image :width="80" :src="record.billUrl" />
              </template>
              <template v-if="column.key === 'bill'">
                <a @click="read(record.parnterId)">查看</a>
              </template>
              <template v-else-if="column.dataIndex === 'operation'">
                <a-popconfirm v-if="dataSource.length" title="确定删除" @confirm="onDelete(record.rowId)">
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </template>
            <template #summary>
              <a-table-summary-row fixed>
                <a-table-summary-cell :index="0">到账金额合计</a-table-summary-cell>
                <a-table-summary-cell :col-span="13">
                  <a-typography-text> {{ saleAmountSum }}</a-typography-text>
                </a-table-summary-cell>
              </a-table-summary-row>
              <a-table-summary-row fixed>
                <a-table-summary-cell :index="0">提成金额合计</a-table-summary-cell>
                <a-table-summary-cell :col-span="13">
                  <a-typography-text> {{ sum }}</a-typography-text>
                </a-table-summary-cell>
              </a-table-summary-row>
            </template>
          </a-table>
          <a-row justify="space-between" class="mt-4">
            <a-col>
              <a-pagination v-model:current="pageNo" :total="totalPage" @change="changePage" />
            </a-col>

            <a-col>
              <a-space class="btn-group"> <a-button type="primary" @click="onSend">发送</a-button>
              </a-space></a-col></a-row>

        </div>
      </a-card>
      <a-modal v-model:visible="infoVisible" title="资料录入" ok-text="提交" cancel-text="取消" width="600px"
        :bodyStyle="{ padding: '24px' }" @ok="onOk">
        <a-form ref="infoRef" :model="infoState" :rules="accountRules" :label-col="{ style: { width: '90px' } }"
          name="basic" autocomplete="off">
          <a-row>
            <a-col :span="12">
              <a-form-item name="name" label="合伙人姓名">
                <a-input v-model:value="infoState.name" /> </a-form-item></a-col>
            <a-col :span="12">
              <a-form-item name="softwareName" label="合作项目">
                <a-input v-model:value="infoState.softwareName" /> </a-form-item></a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item name="rate" label="提成(%)">
                <a-input v-model:value="infoState.rate" /> </a-form-item></a-col>

          </a-row>

        </a-form>
      </a-modal>
      <a-modal v-model:visible="orderVisible" title="上传单据" ok-text="提交" cancel-text="取消" width="600px"
        :bodyStyle="{ padding: '24px' }" @ok="onOrderOk">
        <a-form ref="orderRef" :model="orderState" :rules="orderRules" :label-col="{ style: { width: '90px' } }"
          name="basic" autocomplete="off">
          <a-row>
            <a-col :span="12">
              <a-form-item label="合伙人姓名">
                {{ info.name }}
              </a-form-item></a-col>
            <a-col :span="12">
              <a-form-item label="合作项目">
                {{ info.softwareName }}
              </a-form-item></a-col>
          </a-row>
          <a-row>
            <a-col :span="12">
              <a-form-item label="提成(%)">
                {{ info.rate }}
              </a-form-item></a-col>
            <a-col :span="12">
              <a-form-item name="payDate" label="付款日期">
                <a-date-picker v-model:value="orderState.payDate" style="width: 100%" format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD" /> </a-form-item></a-col>
          </a-row>
          <a-form-item name="file" label="上传单据">
            <a-upload v-model:file-list="fileList" name="file" :headers="headers" :max-count="1"
              :before-upload="beforeUpload" @change="handleChange" :customRequest="customUpload">
              <a-button>
                <upload-outlined></upload-outlined>
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal v-model:visible="performanceVisible" title="当月业绩"  width="1000px" :footer="null"
        :bodyStyle="{ padding: '24px' }" >
        <div>
          <div class="my-4">月份:{{monthNum}}</div>
          <a-table class="ant-table-striped" :columns="columns1" size="small" :data-source="dataSource1" bordered
            :pagination="{ position: ['bottomLeft'] }">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'operation'">
                <a-popconfirm v-if="dataSource1.length" title="确定删除" @confirm="onDel(record.rowId)">
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </template>
            <template #summary>
              <a-table-summary-row fixed>
                <a-table-summary-cell :index="0">到账金额合计</a-table-summary-cell>
                <a-table-summary-cell :col-span="7">
                  <a-typography-text> {{ saleAmountSum }}</a-typography-text>
                </a-table-summary-cell>
              </a-table-summary-row>
              <a-table-summary-row fixed>
                <a-table-summary-cell :index="0">提成金额合计</a-table-summary-cell>
                <a-table-summary-cell :col-span="7">
                  <a-typography-text> {{ sum }}</a-typography-text>
                </a-table-summary-cell>
              </a-table-summary-row>
            </template>
          </a-table>
          <a-row justify="space-between" class="mt-4">
            <a-col>
              <a-pagination v-model:current="pageNo1" :total="totalPage1" @change="changePage1" />
            </a-col>

          </a-row>
        </div>
      </a-modal>
      <!-- 用户注册 -->
      <a-modal v-model:visible="registerVisible" title="注册密码" ok-text="提交" cancel-text="取消"
        :bodyStyle="{ padding: '24px' }" @ok="onRegister">
        <a-form ref="registerRef" :model="registerState" :rules="registerRules"
          :label-col="{ style: { width: '80px' } }" name="basic" autocomplete="off">
          <a-form-item name="account" label="账号">
            <a-input v-model:value="registerState.account" />
          </a-form-item>
          <a-form-item name="password" label="密码">
            <a-input-password v-model:value="registerState.password" />
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
import { message, Upload, Modal } from 'ant-design-vue'
import { UploadOutlined } from '@ant-design/icons-vue'
import { PageWrapper } from '/@/components/Page'
import type { TableProps } from 'ant-design-vue'
import type { UploadChangeParam, UploadProps } from 'ant-design-vue'

import { ref, reactive, onMounted, nextTick } from 'vue'
import type { Rule } from 'ant-design-vue/es/form'
import dayjs from 'dayjs';

import {
  addPartner,
  settleList,
  registerApi,
  delSettle,
  commitSettle,
  sendSettle,
  getSettledetail,
  delSettledetail,
  getSettle
} from '/@/api/sys/settle'
const year = ref()
const month = ref()
const monthNum = ref()
const currentMonth = ref(dayjs().startOf('month'));
const token = localStorage.getItem('TOKEN_KEY')
//当前页码
const pageNo = ref(1)
// 总页码
const totalPage = ref(0)
//总计
const saleAmountSum = ref('')
const sum = ref('')
//当前页码
const pageNo1 = ref(1)
// 总页码
const totalPage1 = ref(0)
//总计
const saleAmountSum1 = ref('')
const sum1 = ref('')



//选中数据
interface DataType {
  rate: string
  softwareName: string
  partnerName: string
  rowId: string
}
const selectedRowKeys = ref<string[]>([])
const selectedRows = ref<DataType[]>([])
const rowSelection: TableProps['rowSelection'] = {
  columnTitle: '选择',
  type: 'radio',
  columnWidth: 120,
  fixed: true,
  preserveSelectedRowKeys: true,
  onChange: (keys: string[], rows: DataType[]) => {
    selectedRowKeys.value = keys
    selectedRows.value = rows
  },
}
//注册密码
const registerVisible = ref<boolean>(false)
const openRegister = () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return
  }
  registerVisible.value = true
}

interface registerValues {
  account: string
  password: string
}
const registerRef = ref()

const registerState = reactive<registerValues>({
  account: '',
  password: '',
})

const registerRules: Record<string, Rule[]> = {
  account: [{ required: true, message: '请输入账号' }],
  password: [{ required: true, message: '请输入密码' }],
}

const onRegister = () => {
  registerRef.value
    .validateFields()
    .then(async (values: any) => {
      const res = await registerApi({
        token,
        data: {
          userId: selectedRowKeys.value[0],
          account: values.account,
          password: values.password,
        },
      })
      if (res.success === 1) {
        message.success('注册成功')
        getTable()
      } else {
        message.error(res.message)
      }
      registerVisible.value = false
      registerRef.value.resetFields()
      // console.log('reset formState: ', toRaw(passwordState))
    })
    .catch((info: any) => {
      console.log('Validate Failed:', info)
    })
}

//资料录入
interface Values {
  name: string
  rate: string
  softwareName: string
}
const infoRef = ref()
const infoVisible = ref<Boolean>(false)
const infoState = ref<Values>({
  rate: '',
  softwareName: '',
  name: '',
})
function addInfo() {
  if (!selectedRows.value || selectedRows.value.length === 0) {

  } else {

    infoState.value.rate = selectedRows.value[0].rate
    infoState.value.name = selectedRows.value[0].partnerName
    infoState.value.softwareName = selectedRows.value[0].softwareName


  }
  infoVisible.value = true
}

const accountRules: Record<string, Rule[]> = {
  name: [{ required: true, message: '请输入姓名' }],
  softwareName: [{ required: true, message: '请输入合作项目' }],
  rate: [{ required: true, message: '请输入提成' }],
}
const onOk = () => {
  infoRef.value
    .validateFields()
    .then(async (values: any) => {
      console.log(values)
      const params = values
      if (!selectedRows.value || selectedRows.value.length === 0) {

      } else {
        params.id = selectedRowKeys.value[0]
      }
      const res = await addPartner({
        token,
        data: params
      })
      if (res.success) {
        message.success('成功')
        getTable()
      } else {
        message.error(res.message)
      }
      infoVisible.value = false
      infoRef.value.resetFields()
    })
    .catch((info: any) => {
      console.log('Validate Failed:', info)
    })
}
//单据
//上传图片
const headers = ref({
  authorization: 'authorization-text',
})
const fileList = ref([])
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList)
  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} file uploaded successfully`)
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} file upload failed.`)
  }
}
// 自定义上传处理
const customUpload = ({ file, onSuccess }) => {
  // 简单示例，直接模拟成功
  setTimeout(async () => {
    orderState.value.file = file
    onSuccess('ok', file);
    await nextTick();
  }, 1000);
}
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isPNG) {
    message.error(`请上传图片格式的文件！`)
  }
  return isPNG || Upload.LIST_IGNORE
}
interface orderValues {
  payDate: string
  file: any

}
const info = ref<Values>({
  rate: '',
  name: '',
  softwareName: ''
})
const orderState = ref<orderValues>({
  payDate: '',
  file: null,
})
const orderRef = ref()
const orderVisible = ref<Boolean>(false)
function addOrder() {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return

  }
  else {

    info.value.rate = selectedRows.value[0].rate
    info.value.name = selectedRows.value[0].partnerName
    info.value.softwareName = selectedRows.value[0].softwareName


  }
  orderVisible.value = true


}

const orderRules: Record<string, Rule[]> = {
  payDate: [{ required: true, message: '请选择日期' }],
  file: [{ required: true, message: '请上传单据' }],
}
const onOrderOk = () => {
  orderRef.value
    .validateFields()
    .then(async (values: any) => {
      console.log(values)
      if (selectedRows.value[0].rowId) {
        const params = values
        params.rowId = selectedRows.value[0].rowId
        const res = await commitSettle(
          {
            token,
            data: params
          }
        )
        if (res.success) {
          message.success('成功')
          getTable()
        } else {
          message.error(res.message)
        }
      } else {
        message.error('该数据未支付')
      }

      orderVisible.value = false
      orderRef.value.resetFields()
    })
    .catch((info: any) => {
      console.log('Validate Failed:', info)
    })
}
//表格

const columns = ref([
  {
    title: '月份',
    dataIndex: 'month',
    key: 'month',
    width: '40',
  },
  {
    title: '合伙人姓名',
    dataIndex: 'partnerName',
    key: 'partnerName',
  },
  {
    title: '账号',
    dataIndex: 'account',
    key: 'account',
  },

  {
    title: '密码',
    dataIndex: 'password',
    key: 'password',
  },
  {
    title: '合作项目',
    dataIndex: 'softwareName',
    key: 'softwareName',
  },
  {
    title: '本月业绩',
    children: [
      {
        title: '租售总金额',
        dataIndex: 'saleAmount',
        key: 'saleAmount',
        width: 80,
      },
      {
        title: '提成(%)',
        dataIndex: 'rate',
        key: 'rate',
        width: 80,
      },
      {
        title: '提成金额',
        dataIndex: 'amount',
        key: 'amount',
        width: 80,
      },
      {
        title: '付款日期',
        dataIndex: 'payDay',
        key: 'payDay',
        width: 80,
      },
      {
        title: '单据',
        dataIndex: 'billUrl',
        key: 'billUrl',
        width: 100,
      },
    ],
  },
  {
    title: '当月业绩',
    dataIndex: 'bill',
    key: 'bill',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '操作',
    fixed: 'right',
    width: 80,
    dataIndex: 'operation',
  },
])
const dataSource = ref([

])
const columns1 = ref([
  {
    title: '用户名',
    dataIndex: 'userName',
    key: 'userName',
    width: '80',
  },
  {
    title: '联系人',
    dataIndex: 'contact',
    key: 'contact',
  },
  {
    title: '手机',
    dataIndex: 'phone',
    key: 'phone',
  },

  {
    title: '租售类别',
    dataIndex: 'rentType',
    key: 'rentType',
  },
  {
    title: '到账金额',
    dataIndex: 'payAmount',
    key: 'payAmount',
  },
  {
    title: '提成金额',
    dataIndex: 'amount',
    key: 'amount',
  },


  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '操作',
    fixed: 'right',
    width: 80,
    dataIndex: 'operation',
  },
])
const dataSource1 = ref([
])
//业绩
const targetId = ref()
const performanceVisible = ref<Boolean>(false)
const read = (key: string) => {
  console.log(key)
  targetId.value = key
  getPerformance()

}
//获取业绩
const getPerformance = async () => {
  const params = {
    year: year.value,
    month: month.value,
    token: token,
    pageNo: pageNo1.value,
    partnerId: targetId.value
  }
  console.log(params)

  const res = await getSettledetail(params)
  if (res.success == 1) {
    performanceVisible.value = true
    totalPage1.value = res.data.totalPage
    dataSource1.value = res.data.items
    monthNum.value=res.data.month
    sum1.value = res.data.sum.amountSum
    saleAmountSum1.value = res.data.sum.saleAmountSum
  }

}
const onDelete = async (key: string) => {
  if (key) {
    const res = await delSettle({
      token,
      data: { ids: [key] },
    })
    if (res.success == 1) {
      message.success('删除成功')
      getTable()
    } else {
      message.error(res.message)
    }
  } else {
    message.error(' 该数据未支付')

  }
}
const onDel= async (key: string) => {
  if (key) {
    const res = await delSettledetail({
      token,
      data: { ids: [key] },
    })
    if (res.success == 1) {
      message.success('删除成功')
      getPerformance()
    } else {
      message.error(res.message)
    }
  } else {
    message.error(' 该数据未支付')

  }
}
const onSend = async () => {
  if (!selectedRows.value || selectedRows.value.length === 0) {
    message.warning('请先选择一项数据')
    return
  }
  if (selectedRows.value[0].rowId) {
    const res = await sendSettle({
      token,
      data: { ids: selectedRows.value[0].rowId },
    })
    if (res.success == 1) {
      message.success('删除成功')
      getTable()
    } else {
      message.error(res.message)
    }
  } else {
    message.error(' 该数据未支付')
  }

}
async function getTable() {
  const params = {
    year: year.value,
    month: month.value,
    token: token,
    pageNo: pageNo.value,
  }
  const res = await settleList(params)
  totalPage.value = res.data.totalPage
  dataSource.value = res.data.items
  sum.value = res.data.sum.amountSum
  saleAmountSum.value = res.data.sum.saleAmountSum
}
async function createSettle() {
  const params = {
    year: year.value,
    month: month.value,
    token: token,
  }
  const res = await getSettle(params)
  totalPage.value = res.data.totalPage
  dataSource.value = res.data.items
  sum.value = res.data.sum.amountSum
  saleAmountSum.value = res.data.sum.saleAmountSum
}

function changePage() {
  getTable()
}
function changePage1() {
  getPerformance()
}

const changePicker = (date) => {
  year.value = date.split('-')[0]
  month.value = date.split('-')[1]
  getTable()

}
// 页面加载时自动执行
onMounted(() => {
  createSettle()

})
</script>
<style scoped lang="less">
#commission {
  .top {
    a {
      color: #333;
    }
  }

  .btn-group {
    display: flex;
    justify-content: end;
    margin-top: 20px;
  }
}
</style>
